package com.yiyi.service.impl;

import com.yiyi.entity.StudentLongyiyi;
import com.yiyi.form.SearchStudentForm;
import com.yiyi.repository.StudentRepository;
import com.yiyi.service.StudentService;
import com.yiyi.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * 学生信息服务接口实现类
 *
 * @author yiyi
 * @date 2021/6/23
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    /**
     * 根据id获取实体详细信息
     *
     * @param id
     * @return
     * */
    @Override
    public StudentLongyiyi findById(Integer id) {
        return studentRepository.findById(id).get();
    }

    /**
     * 分页展示及搜索。
     * 因为jpa中的特性，需要给使用 like 进行模糊查询的字符串两边都加上 %。
     *
     * @param form
     * @return
     * */
    @Override
    public PageVO findByPage(SearchStudentForm form) {
        PageVO pageVO = new PageVO();
        // 为字符串搜索变量左右添加 %
        String searchName = "%" + form.getStudentName() + "%";
        form.setStudentName(searchName);
        String searchClass = "%" + form.getStudentClass() + "%";
        form.setStudentClass(searchClass);

        Pageable pageable = PageRequest.of(form.getNumber() - 1, form.getSize());
        Page<StudentLongyiyi> page = studentRepository.findByPage(pageable, form);

        // 组装VO
        pageVO.setNumber(page.getNumber());
        pageVO.setSize(page.getSize());
        pageVO.setPages(page.getTotalPages());
        pageVO.setTotal(page.getTotalElements());
        pageVO.setList(page.getContent());

        return pageVO;
    }

    /**
     * 保存实体，可被新增和修改对象接口调用
     *
     * @param student
     * @return
     * */
    @Override
    public boolean saveOne(StudentLongyiyi student) {
        StudentLongyiyi studentLongyiyi = studentRepository.save(student);
        if (studentLongyiyi != null) {
            return true;
        }
        return false;
    }

    /**
     * 删除实体
     *
     * @param id
     * */
    @Override
    public void deleteOne(Integer id) {
        studentRepository.deleteById(id);
    }
}
